<?php

/**
 * @author      Alex Bilbie <hello@alexbilbie.com>
 * @copyright   Copyright (c) Alex Bilbie
 * @license     http://mit-license.org/
 *
 * @link        https://github.com/thephpleague/oauth2-server
 */

declare(strict_types=1);

namespace app\oauth\Repositories;

use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use app\oauth\Entities\ClientEntity;

use function array_key_exists;
use function password_hash;
use function password_verify;


use app\oauth\model\OauthClients as OauthClientsModel; //引入模型

class ClientRepository implements ClientRepositoryInterface
{




    /**
     * @return ClientEntityInterface
     */
    public function getClientEntity($clientIdentifier, $grantType = null, $clientSecret = null, $mustValidateSecret = true)
    {

        
        $oauth_clients = OauthClientsModel::where('id', $clientIdentifier)->find();

        if (empty($oauth_clients)) {
            return;
        }

        // 获取客户端对象时调用方法，用于验证客户端
        // 需要返回 ClientEntityInterface 对象
        // $clientIdentifier 客户端唯一标识符
        // $grantType 代表授权类型，根据类型不同，验证方式也不同
        // $clientSecret 代表客户端密钥，是客户端事先在授权服务器中注册时得到的
        // $mustValidateSecret 代表是否需要验证客户端密钥

        $client_entity = new ClientEntity();
        $client_entity->setIdentifier($clientIdentifier);
        $client_entity->setName($oauth_clients->name);
        $client_entity->setRedirectUri($oauth_clients->redirect);
        $client_entity->setConfidential();
        return $client_entity;
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateClient($clientIdentifier, $clientSecret, $grantType): bool
    {
        
        $oauth_clients = OauthClientsModel::where('id', $clientIdentifier)->find();
        // Check if client is registered
        if (empty($oauth_clients)) {
            return false;
        }



        // if (empty($oauth_clients) || ! $this->handlesGrant($record, $grantType)) {
        //     return false;
        // }

        // if (password_verify($clientSecret, $clients[$clientIdentifier]['secret']) === false) {
        //     return false;
        // }
        
        return true;
    }



}
